package com.example.yimai.interceptor;

import com.example.yimai.utils.JWTUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTAuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(token != null && token.startsWith("Bearer ")){
            //获取实际的token
            token = token.substring(7);

            //验证token
            if(jwtUtil.validateToken(token) && redisTemplate.opsForValue().get(jwtUtil.getLoginName(token)) != null){
                String loginName = jwtUtil.getLoginName(token);
                String userId = jwtUtil.getId(token);
                //将用户信息存入request中
                request.setAttribute("id", userId);
                request.setAttribute("userId", userId);
                request.setAttribute("loginName",loginName);
                request.setAttribute("type",jwtUtil.getType(token));

                return true;
            }

        }

        //验证未通过，返回401
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"message\":\"无效的token\"}");
        return false;
    }
}
